package com.gm.census.web.interceptors;

import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends UserInterceptor {

	private static final Logger log = Logger.getLogger(LoginInterceptor.class
			.getName());

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object hnd) throws Exception {
		boolean logged = getUserService().isUserLoggedIn();
		if (logged) {
			populateSession(request);
		} else {
			String url = getUserService().createLoginURL(
					request.getRequestURI());
			response.sendRedirect(url);
		}
		return logged;
	}

	protected void populateSession(HttpServletRequest request) {
		request.setAttribute("permissions", getPermissions());
		request.setAttribute("logout",
				getUserService().createLogoutURL(request.getRequestURI()));
		request.setAttribute("logged", getUserService().getCurrentUser());
	}

	protected HashMap<String, Boolean> getPermissions() {
		HashMap<String, Boolean> permissions = new HashMap<String, Boolean>();
		if (getUserService().isUserAdmin())
			permissions.put("admin", true);
		return permissions;
	}
}
